import random
import string
import time

from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from commodity.models import CommodityInfo
from shopper.form import LoginForm, LoginModelForm
from shopper.models import OrderInfos, CartInfos
from shopper.pays import get_pay


# Create your views here.

@login_required(login_url='/shopper/login.html')
def shopperView(request):
    """
    没登录就去登录
    """
    title = '个人中心'
    classContent = "information-content"
    t = request.GET.get('t', '')
    p = request.GET.get('p', '')
    payTime = request.GET.get('payTime', '')
    if t and payTime and t == payTime:
        # 两者不为空,且相等说明支付成功
        payInfo = request.session.get('payInfo', '')
        OrderInfos.objects.create(**payInfo)
        del request.session['payInfo']
        del request.session['payTime']
    orderInfos = OrderInfos.objects.filter(user_id=request.user.id).order_by('-created')
    # 分页
    paginator = Paginator(orderInfos, 7)
    try:
        pages = paginator.page(p)
    except PageNotAnInteger:
        pages = paginator.page(1)
    except EmptyPage:
        pages = paginator.page(paginator.num_pages)
    return render(request, 'shopper.html', locals())


def loginView(request):
    """
    登录和注册
    """
    title = '用户登录'
    classContent = 'login-content'
    if request.method == 'POST':
        # infos = LoginForm(data=request.POST)
        infos = LoginModelForm(data=request.POST)

        # 验证数据是否正确
        #     if infos.is_valid():
        #         data = infos.cleaned_data
        #         # 执行登录操作
        #         # username = request.POST.get('username', '')
        #         # password = request.POST.get('password', '')
        #         username = data['username']
        #         password = data['password']
        #         if User.objects.filter(username=username):
        #             user = authenticate(username=username, password=password)
        #             if user:
        #                 login(request, user)
        #                 return redirect(reverse('shopper:shopper'))
        #         else:
        #             # 注册
        #             state = "注册成功"
        #             d = dict(username=username, password=password, is_staff=1, is_active=1)
        #             user = User.objects.create_user(**d)
        #             user.save()
        #     else:
        #         # 获取错误信息，输出
        #         error_msg = infos.errors.as_json()
        #         print(error_msg)
        # else:
        #     # get请求
        #     infos = LoginForm()
        # if infos.is_valid():
        data = infos.data
        # 执行登录操作
        # username = request.POST.get('username', '')
        # password = request.POST.get('password', '')
        username = data['username']
        password = data['password']
        if User.objects.filter(username=username):
            user = authenticate(username=username, password=password)
            if user:
                login(request, user)
                return redirect(reverse('shopper:shopper'))
        else:
            # 注册
            state = "注册成功"
            d = dict(username=username, password=password, is_staff=1, is_active=1)
            user = User.objects.create_user(**d)
            user.save()
    else:
        # get请求
        infos = LoginModelForm()
    return render(request, "login.html", locals())


def logoutView(request):
    logout(request)
    return redirect(reverse('index:index'))

@login_required(login_url='/shopper/login.html')
def shopcartView(request):
    title = '我的购物车'
    classContent = "shopcart-content"
    # items = CommodityInfo.objects.
    userId = request.user.id

    id = request.GET.get('id', '')
    quantity = request.GET.get('quantity', 1)

    # 判断id是否为空，
    # 正确就触发购买按钮
    if id:
        CartInfos.objects.update_or_create(
            commodityInfos_id=id,
            user_id=userId,
            defaults={'quantity':quantity}
        )
        # 操作成功后，重定向
        return redirect(reverse('shopper:shopcart'))
    getUserId = CartInfos.objects.filter(user_id=userId)
    commodityDict = {x.commodityInfos_id : x.quantity for x in getUserId}
    commodityInfos = CommodityInfo.objects.filter(id__in=commodityDict.keys())
    return render(request, "shopcart.html", locals())

def deleteAPI(request):
    """
    按用户删除或者按商品id删除
    """
    # 如果state是fail，那么删除失败
    result = {'state' : 'success'}

    userId = request.GET.get('userId', '')
    commodityId = request.GET.get('commodityId', '')
    if userId:
        CartInfos.objects.filter(user_id=userId).delete()
    elif commodityId:
        CartInfos.objects.filter(commodityInfos_id=commodityId).delete()
    else:
        result= {'state': 'fail'}
    return JsonResponse(result)

def paysView(request):
    total = request.GET.get('total', 0)
    total = total.replace('￥', '')
    try:
        total = float(total)
    except ValueError:
        return redirect('shopper:shopcart')
    if total > 0:
        timestamp = int(time.time() * 1000)
        random_str = "".join(random.choices(string.digits, k=6))
        out_trade_no = f"{timestamp}{random_str}"
        total_amount = "{:.2f}".format(total)
        payInfo = dict(price=total, user_id=request.user.id, state="已支付")
        request.session['payInfo'] = payInfo
        request.session['payTime'] = out_trade_no
        domain = 'htpp://' + request.get_host()
        return_url = f"{domain}/shopper/pay_callback/"
        print(f"out_trade_no:{out_trade_no}, type:{type(out_trade_no)}")
        print(f"total_amount:{total_amount},type:{type(total_amount)}")
        print(f"return_url:{return_url},type:{type(return_url)}")
        url = get_pay(out_trade_no, total_amount, return_url)
        print("支付宝链接:", url)
        if url:
            return redirect(url)
        else:
            return redirect('shopper:shopcart')
    else:
        return redirect('shopper:shopcart')

def payCallbackView(request):
    """
    支付完，回调函数
    """
    payTime = request.session.get('payTime', '')
    if payTime:
        payInfo = request.session.get('payInfo', '')
        if payInfo:
            OrderInfos.objects.create(**payInfo)
            del request.session['payInfo']
            del request.session['payTime']
    return redirect(reverse('shopper:shopper'))